let services = module.exports;

//庄家只能赢身上数量的钱
services.reWinScore = function (userWinScores, winUserKey, winUserScore, userSortList) {

    let winScores = {};
    winScores[winUserKey] = 0;
    let loseIDList = [];
    for (let key in userWinScores) {
        if (key != winUserKey) {
            let curScore = userWinScores[key];
            if (curScore >= 0) {
                winScores[winUserKey] -= curScore; //庄家输分
                winScores[key] = curScore; //玩家赢分
            } else {
                loseIDList.push(parseInt(key)); //玩家输了 等待后面分配
            }
        }
    }
    //庄家最多可以赢的分
    let totalScore = winUserScore + Math.abs(winScores[winUserKey]);
    for (let i = 0; i < userSortList.length; i++) {
        let userKey = userSortList[i].key;
        if (loseIDList.includes(parseInt(userKey))) {
            let userLoseScore = Math.abs(userWinScores[userKey])
            //统计玩家输赢
            if (totalScore > userLoseScore) {
                winScores[userKey] = -userLoseScore; //玩家输分
                winScores[winUserKey] += userLoseScore; //庄家赢分
                totalScore -= userLoseScore;
            } else if (totalScore <= userLoseScore) {
                winScores[userKey] = -totalScore; //玩家输分
                winScores[winUserKey] += totalScore; //庄家赢分
                totalScore = 0;
            }
        }
    }
    return winScores;
}

//庄家只能输身上数量的钱
services.reLoseScore = function (userWinScores, loseUserKey, winUserScore, userSortList) {

    let winScores = {};
    winScores[loseUserKey] = 0;
    let winIDList = [];
    for (let key in userWinScores) {
        if (key != loseUserKey) {
            let curScore = userWinScores[key];
            if (curScore < 0) {
                curScore = Math.abs(curScore);
                winScores[loseUserKey] += curScore; //庄家赢分
                winScores[key] = -curScore; //玩家输分
            } else {
                winIDList.push(parseInt(key)); //玩家赢了 等待后面分配
            }
        }
    }
    //庄家最多可以输的分
    let totalScore = winUserScore + winScores[loseUserKey];

    for (let i = 0; i < userSortList.length; i++) {
        let userKey = userSortList[i].key;
        if (winIDList.includes(parseInt(userKey))) {
            let userCurScore = userWinScores[userKey];
            //统计玩家输赢
            if (totalScore > userCurScore) {
                winScores[userKey] = userCurScore; //玩家赢分
                winScores[loseUserKey] -= userCurScore; //庄家输分
                totalScore -= userCurScore;
            } else if (totalScore <= userCurScore) {
                winScores[userKey] = totalScore; //玩家赢分
                winScores[loseUserKey] -= totalScore; //庄家输分
                totalScore = 0;
            }
        }
    }
    return winScores;
}